// cookie.controller.ts
//
import {
  Controller,
  Post,
  Body,
  Get,
  Query,
  BadRequestException,
  Logger,
} from '@nestjs/common';
import { PrismaService } from '../database/prisma.service';
import { CreateGoodsDto, CreateManyGoodsDto } from './dto/create-goods.dto';
import { PaginationDto, TimingnationQueryDto } from './dto/list-goods.dto';
import { ApiResponse, ApiOperation, ApiQuery } from '@nestjs/swagger';

@Controller('goods')
export class GoodsController {
  constructor(private readonly prismaService: PrismaService) {}
  @Get('list')
  async listGoods() {
    try {
      return await this.prismaService.goods.findMany({});
    } catch (error) {
      throw new BadRequestException(`Failed to list goods: ${error.message}`);
    }
  }
  @ApiOperation({ summary: 'Timingnation query goods' })
  @ApiQuery({
    name: 'from',
    type: String,
    required: true,
    description: 'Start date in ISO8601 format',
  })
  @ApiQuery({
    name: 'to',
    type: String,
    required: true,
    description: 'To date',
  })
  @ApiResponse({
    status: 200,
    description: '{message:messag,goods:[]',
  })
  @Get('timingnation')
  async Timingnation(@Query() query: TimingnationQueryDto) {
    console.log(query);
    const { from, to } = query;
    Logger.log(`Timingnation query goods from ${from} to ${to}`);
    const fromDate = new Date(from);
    const toDate = new Date(to);
    const data = await this.prismaService.goods.findMany({
      where: {
        updateTime: {
          gte: fromDate,
          lte: toDate,
        },
      },
    });

    return {
      message: 'Timingnation query successful',
      data,
    };
  }
  @Get('pagination')
  @ApiOperation({ summary: 'pagination the goods list' })
  @ApiResponse({
    status: 200,
    description: '{message:message,page,size,goods:[]}',
  })
  async pagination(@Query() query: PaginationDto) {
    const { page, size } = query;
    Logger.log(`pagination goods page:${page} pageSize:${size} `);
    const [total, data] = await this.prismaService.$transaction([
      this.prismaService.goods.count({}),
      this.prismaService.goods.findMany({
        skip: size * page,
        take: size,
      }),
    ]);
    return { total, data };
  }
  // Create Cookie via JSON (string content)
  @Post()
  async createGoods(@Body() goods: CreateGoodsDto) {
    try {
      const goodsCreated = await this.prismaService.goods.create({
        data: goods,
      });
      return goodsCreated;
    } catch (error) {
      throw new BadRequestException(
        `Failed to create cookie: ${error.message}`,
      );
    }
  }
  @Post('many')
  @ApiOperation({ summary: 'Create multiple goods entries' })
  @ApiResponse({ status: 201, description: 'Goods created successfully' })
  async createManyGoods(@Body() createManyGoodsDto: CreateManyGoodsDto) {
    if (!createManyGoodsDto?.data || !Array.isArray(createManyGoodsDto.data)) {
      throw new Error('Request must include a valid "data" array');
    }
    try {
      const goodsCreated = await this.prismaService.goods.createMany({
        data: createManyGoodsDto.data,
      });

      return goodsCreated;
    } catch (error) {
      throw new BadRequestException(`Failed to create goods: ${error.message}`);
    }
  }
}
